<template>
  <div class="app-container">
    <v-row :gutter="20">
      <v-col>
        <!-- 搜索表单 -->
        <v-form ref="queryForm" v-show="showSearch" label-width="68px">
          <v-row>
            <v-col md="2" style="padding-bottom: 2px">
              <v-text-field
                label="角色名称"
                v-model="queryParams.roleName"
                placeholder="请输入角色名称"
                outlined
                dense
                clearable
                @keyup.enter.native="handleQuery"
                style="width: 240px;"
              ></v-text-field>
            </v-col>
            <v-col md="2" style="padding-bottom: 2px">
              <v-text-field
                label="权限字符"
                v-model="queryParams.roleKey"
                placeholder="请输入权限字符"
                hide-details="auto"
                outlined
                dense
                style="width: 240px;"
                @keyup.enter.native="handleQuery"
              ></v-text-field>
            </v-col>
            <v-col md="2" style="padding-bottom: 2px;max-width: 150px">
              <v-select
                label="角色状态"
                v-model="queryParams.status"
                :items="statusOptions"
                item-text="dictLabel"
                item-value="dictValue"
                dense
                outlined
                clearable
                style="width: 130px;"
              ></v-select>
            </v-col>
            <v-col cols="12"
                   sm="6"
                   md="2" style="padding-bottom: 2px;max-width: 180px">
              <v-menu
                ref="dateRangeMenu"
                v-model="dateRangeMenu"
                :close-on-content-click="false"
                transition="scale-transition"
                offset-y
                max-width="240px"
                min-width="auto"
                style="width: 240px;padding-top: 0;margin-top: 0"
              >
                <template v-slot:activator="{ on, attrs }">
                  <v-text-field
                    v-model="date"
                    label="创建时间"
                    prepend-icon="mdi-calendar"
                    v-bind="attrs"
                    @blur="date = parseDate(dateFormatted)"
                    v-on="on"
                    clearable
                    style="width: 240px;padding-top: 0"
                  ></v-text-field>
                </template>
                <v-date-picker
                  v-model="date"
                  no-title
                  @input="dateRangeMenu = false"
                  style="padding: 0"
                ></v-date-picker>
              </v-menu>
            </v-col>

            <!-- 按钮区-->
            <v-col cols="12"
                   sm="6"
                   md="2" style="padding-bottom: 0;margin-left: 1rem;height: 40px;margin-top: 8px">
              <p style="display: inline-block;position: absolute">
                <v-btn
                  small color="primary"
                  :loading="loading"
                  @click="handleQuery">
                  <v-icon left>
                    mdi-magnify
                  </v-icon>
                  搜索
                </v-btn>
                <v-btn
                  small
                  :loading="loading"
                  @click="resetQuery"
                  style="margin-left: 10px"
                >
                  <v-icon left>
                    mdi-autorenew
                  </v-icon>
                  重置
                </v-btn>
              </p>
            </v-col>
          </v-row>
        </v-form>
      </v-col>
    </v-row>

    <!-- 表格操作按钮区 -->
    <v-row style="margin-bottom: -5px;margin-top: 0;">
      <v-col md="1" style="max-width: 84px">
        <v-btn
          color="primary"
          plain
          small
          outlined
          @click="handleAdd"
          v-hasPermi="['system:role:add']">
          <v-icon left>
            mdi-plus
          </v-icon>
          新增
        </v-btn>
      </v-col>
      <v-col md="1" style="max-width: 84px">
        <v-btn
          small
          plain
          outlined
          :disabled="single"
          @click="handleUpdate(ids[0])"
          v-hasPermi="['system:role:edit']">
          <v-icon left>
            mdi-pencil
          </v-icon>
          修改
        </v-btn>
      </v-col>
      <!--todo 二次确认删除按钮 -->
      <v-col md="1" style="max-width: 84px">
        <v-btn
          small color="error"
          plain
          outlined
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:role:remove']">
          <v-icon left>
            mdi-delete
          </v-icon>
          删除
        </v-btn>
      </v-col>
      <v-col md="1" style="max-width: 84px">
        <v-btn
          type="warning"
          small
          plain
          outlined
          @click="handleExport"
          v-hasPermi="['system:role:export']">
          <v-icon left>
            mdi-upload
          </v-icon>
          导出
        </v-btn>
      </v-col>
      <v-col style="float: right">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </v-col>
    </v-row>

    <!-- 表格-->
    <v-main>
      <v-data-table v-if="roleList"
            v-model="ids"
            :headers="headers"
            :items="roleList"
            :items-per-page="queryParams.pageSize"
            hide-default-footer
            :loading="loading"
            loading-text="加载中,请稍后.."
            show-select
            item-key="roleId"
            class="elevation-1"
            no-data-text="暂无数据"
      >
        <!-- 状态插槽 -->
        <template v-slot:item.status="{ item }">
          <div v-if="item.status === '1'">正常</div>
          <div v-if="item.status === '0'" style="color: red">停用</div>
        </template>

        <!-- 按钮插槽 -->
        <template v-slot:item.actions="{ item }">
          <v-btn text
                 small
                 plain
                 height="20"
                 width="40"
                 @click="handleUpdate(item)"
                 v-hasPermi="['system:role:edit']">
            <v-icon small>
              mdi-pencil
            </v-icon>
            修改
          </v-btn>
          <v-btn text
                 small color="indigo"
                 plain
                 height="20"
                 width="40"
                 @click="handleDataScope(item)"
                 v-hasPermi="['system:role:edit']" style="margin-left: 13px;margin-right: 13px">
            <v-icon small>
              mdi-account-key
            </v-icon>
            数据权限
          </v-btn>
          <!-- 删除确认 -->
          <span v-if="item && item.showConfirmDelete">
            <v-tooltip top>
              <template v-slot:activator="{ on, attrs }">
                <v-btn
                  small color="error"
                  plain
                  height="20"
                  width="40"
                  v-bind="attrs"
                  v-on="on"
                  @click="handleDelete(item)"
                  v-hasPermi="['system:role:remove']">
                  <v-icon small>
                    mdi-delete
                  </v-icon>
                  确定
                </v-btn>
              </template>
              <span>请再次点击确定删除</span>
            </v-tooltip>
          </span>
          <span v-if="item && !item.showConfirmDelete">
            <v-btn color="#C62828"
                   small
                   plain
                   height="20"
                   width="40"
                   @click="onClickDelete(item)">
              <v-icon small>
                mdi-delete
              </v-icon>
              删除
            </v-btn>
          </span>
        </template>
      </v-data-table>
      <!-- 外部分页-->
      <div class="d-flex align-center justify-end text-center">
        <div class="d-flex" style="margin-top: 3px;font-size: 14px;font-weight: 400">
          <span>每页</span>
          <v-select
            v-model="queryParams.pageSize"
            :items="numbers"
            dense
            @change="getList" style="max-width: 80px;max-height: 20px;margin-top: -4px;text-align: center;">
            <template v-slot:selection="{ item, index }">
                  <span style="width: 100%">
                    {{item}}
                  </span>
            </template>
          </v-select>
          <span>条记录</span>
        </div>
        <v-pagination
          v-model="queryParams.pageNum"
          @input="getList"
          :length="queryParams.totalPages"
          :total-visible="7"
        ></v-pagination>
      </div>
    </v-main>

    <!-- 分配角色数据权限对话框 -->
    <v-dialog
      v-model="openDataScope"
      persistent
      transition="dialog-bottom-transition"
      max-width="500px">

      <v-card >
        <!-- 对话框标题 -->
        <v-card-title>
          <span style="font-size: 18px">分配数据权限</span>
        </v-card-title>

        <!-- 表单 -->
        <v-form ref="form" style="max-height: 500px;overflow: auto;">
          <v-card-text>
            <v-container>
              <v-row>
                <v-col cols="12" sm="10" >
                  <v-text-field
                    label="角色名称"
                    v-model="form.roleName"
                    dense
                    readonly
                  ></v-text-field>
                </v-col>

                <v-col cols="12" sm="10">
                  <v-text-field
                    label="权限字符"
                    v-model="form.roleKey"
                    required
                    dense
                    readonly
                  ></v-text-field>
                </v-col>

                <v-col cols="12" sm="7">
                  <v-select
                    label="权限范围"
                    v-model="form.dataScope"
                    :items="dataScopeOptions"
                    item-text="label"
                    item-value="value"
                    dense
                    @change="dataScopeSelectChange"
                  ></v-select>
                </v-col>

                <v-col cols="12" sm="12" style="padding: 0;" v-show="form.dataScope == 2">
                  <div style="display: inline-block;">
                    <v-card-title style="margin: 0;padding-top: 0;padding-bottom: 0;width: 100px">
                      <span style="font-size: 16px;font-weight: 400;">数据权限</span>
                    </v-card-title>
                    <v-checkbox
                      v-model="deptExpand"
                      label="折叠"
                      color="indigo"
                      dense
                      @change="handleCheckedTreeExpand"
                      title="(未实现展开全部)"
                      style="margin-top: -32px;margin-left: 80px;width: 100px"
                    ></v-checkbox>
                    <v-checkbox
                      v-model="deptNodeAll"
                      label="全选/全不选"
                      color="indigo"
                      dense
                      @change="handleCheckedTreeExpand"
                      title="(未实全选/全不选)"
                      disabled
                      style="margin-top: -47px;margin-left: 175px;"
                    ></v-checkbox>
                    <v-checkbox
                      v-model="form.deptCheckStrictly"
                      label="父子联动"
                      color="indigo"
                      @change="handleCheckedTreeConnect"
                      dense style="margin-top: -47px;margin-left: 320px;"
                    ></v-checkbox>
                  </div>

                  <v-container fluid style="border: indigo 1px solid;border-radius: 3px;width: 95%;margin: 0 auto;">
                    <v-treeview
                      ref="deptTreeRef"
                      :openAll="deptExpand"
                      dense
                      activatable
                      hoverable
                      selectable
                      :selection-type="selectionType"
                      :items="deptOptions"
                      item-key="id"
                      v-model="form.deptIds"
                      style="font-size: 14px;padding: 0;background-color: white;"
                    >
                      <!--插槽-->
                      <template v-slot:prepend="{ item, open }">
                        <div style="min-width: 180px;max-width: 240px;overflow: hidden">
                          {{ item.label }}
                        </div>
                      </template>
                    </v-treeview>
                  </v-container>
                </v-col>
              </v-row>
            </v-container>
          </v-card-text>
        </v-form>

        <!-- 底部操作按钮 -->
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn
            text
            @click="cancelDataScope">
            取消
          </v-btn>
          <v-btn
            color="blue darken-1"
            text
            @click="submitDataScope">
            确定
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <role-add ref="addRoleRef" :visible="showAdd" @updateVisible="updateVisible" @done="handleQuery"
              :menuOptions="menuOptions" :statusOptions="statusOptions"></role-add>
    <role-edit ref="editRoleRef" :visible="showEdit" :data="form" @updateVisible="updateVisible" @done="handleQuery"
              :menuOptions="menuOptions" :statusOptions="statusOptions"></role-edit>
  </div>
</template>

<script>
import { listRole, getRole, delRole, addRole, updateRole, dataScope, changeRoleStatus } from "@/api/system/role";
import { treeselect as menuTreeselect, roleMenuTreeselect } from "@/api/system/menu";
import { treeselect as deptTreeselect, roleDeptTreeselect } from "@/api/system/dept";
import { commonUtils } from "@/utils/commonUtils";
import RoleAdd from "./roleAdd";
import RoleEdit from "./roleEdit";

export default {
  name: "Role",
  components: {
    RoleAdd, RoleEdit
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      showAdd: false,
      showEdit: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true, // 展开，这贴
      deptNodeAll: false, // 全选、全不选
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      // 数据范围选项
      dataScopeOptions: [
        {
          value: "1",
          label: "全部数据权限"
        },
        {
          value: "2",
          label: "自定数据权限"
        },
        {
          value: "3",
          label: "本部门数据权限"
        },
        {
          value: "4",
          label: "本部门及以下数据权限"
        },
        {
          value: "5",
          label: "仅本人数据权限"
        }
      ],
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleName: undefined,
        roleKey: undefined,
        totalPages: 0, // 总页数
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" }
        ],
        roleKey: [
          { required: true, message: "权限字符不能为空", trigger: "blur" }
        ],
        roleSort: [
          { required: true, message: "角色顺序不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "请选择状态", trigger: "blur" }
        ]
      },
      headers: [
        {
          text: '角色编号',
          align: 'center',
          value: 'roleId',
        },
        { text: '角色名称', value: 'roleName', sortable: false, align: 'center' },
        { text: '权限字符', value: 'roleKey', sortable: false, align: 'center' },
        { text: '显示顺序', value: 'dept.roleSort', align: 'center' },
        { text: '状态', value: 'status', sortable: false, align: 'center' },
        { text: '操作', value: 'actions', sortable: false, align: 'center' },
      ],
      numbers: [10, 15, 20, 50, 100], // 每页条数选择
      date: null,
      dateRangeMenu: false,
      dateFormatted: commonUtils.formatDate((new Date(Date.now() - (new Date()).getTimezoneOffset() * 60000)).toISOString().substr(0, 10)),
      selectionTypeCheck: true, // 父子联动
      selectionType: 'leaf' // 父子联动
    };
  },
  watch: {
    ids() {
      this.handleSelectionChange();
    },
    date (val) {
      this.dateFormatted = this.formatDate(this.date)
    },
  },
  created() {
    this.getList();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    /** 查询角色列表 */
    getList() {
      this.ids = [];
      this.loading = true;
      listRole(this.queryParams).then(response => {
        this.roleList = response.rows;
        this.total = response.total;
        this.queryParams.totalPages = Math.ceil(this.total / this.queryParams.pageSize);
        this.loading = false;
      });
    },
    /** 查询菜单树结构 */
    getMenuTreeSelect() {
      menuTreeselect().then(response => {
        this.menuOptions = response.data;
      });
    },
    /** 查询部门树结构 */
    getDeptTreeSelect() {
      deptTreeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.dept.getCheckedKeys();
      // 半选中的部门节点
      let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    /** 根据角色ID查询部门树结构 */
    getRoleDeptTreeselect(roleId) {
      return roleDeptTreeselect(roleId).then(response => {
        this.deptOptions = response.depts;
        return response;
      });
    },
    // 角色状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$confirm('确认要"' + text + '""' + row.roleName + '"角色吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return changeRoleStatus(row.roleId, row.status);
        }).then(() => {
          this.msgSuccess(text + "成功");
        }).catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false;
      this.reset();
    },
    updateVisible(value) {
      this.showAdd = value;
      this.showEdit = value;
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.menuExpand = false,
      this.menuNodeAll = false,
      this.deptExpand = true,
      this.deptNodeAll = false,
      //this.form = {
      //  roleId: undefined,
      //  roleName: undefined,
      //  roleKey: undefined,
      //  roleSort: 0,
      //  status: "1",
      //  menuIds: [],
      //  deptIds: [],
      //  menuCheckStrictly: true,
      //  deptCheckStrictly: true,
      //  remark: undefined
      //};
      this.form = {};
      //this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.date) {
        this.queryParams.createTime = this.date;
      } else {
        this.queryParams.createTime = null;
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.$refs.queryForm.reset(); // 重置
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange() {
      this.single = this.ids.length !== 1;
      this.multiple = !this.ids.length;
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(val, type) {
      this.deptExpand = val
      this.$refs.deptTreeRef.updateAll();
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions: []);
      } else if (type == 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions: []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (value) {
        this.selectionType = 'leaf';
      } else {
        this.selectionType = 'independent'
      }
      //if (type == 'menu') {
      //  this.form.menuCheckStrictly = value ? true: false;
      //} else if (type == 'dept') {
      //  this.form.deptCheckStrictly = value ? true: false;
      //}
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.getMenuTreeSelect();
      this.showAdd = true;
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.form = {};
      const roleId = row.roleId || this.ids;
      await roleMenuTreeselect(roleId).then(response => {
        this.menuOptions = response.menus;
        getRole(roleId).then(res => {
          //this.form = res.data;
          let temp = res.data;
          if (response.checkedKeys) { temp.menuIds = response.checkedKeys } else temp.menuIds = [];
          this.form = temp;
          this.showEdit = true;
        });
      });
    },
    /** 选择角色权限范围触发 */
    dataScopeSelectChange(value) {
      if(value !== '2') {
        //this.$refs.dept.setCheckedKeys([]);
        this.form.deptIds = []; // 置空
      }
    },
    /** 分配数据权限操作 */
    handleDataScope(row) {
      this.reset();
      const roleDeptTreeselect = this.getRoleDeptTreeselect(row.roleId);
      getRole(row.roleId).then(response => {
        //this.form = response.data;
        let tempForm = response.data;
        this.$nextTick(() => {
          roleDeptTreeselect.then(res => {
            //this.$refs.dept.setCheckedKeys(res.checkedKeys);
            if (res.checkedKeys) {
              tempForm.deptIds = res.checkedKeys; // 回显选中的部门
            } else {
              tempForm.deptIds = [];
            }
            this.form = tempForm;
            this.openDataScope = true;
          });
        });
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.roleId != undefined) {
            this.form.menuIds = this.getMenuAllCheckedKeys();
            updateRole(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.menuIds = this.getMenuAllCheckedKeys();
            addRole(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 提交按钮（数据权限） */
    submitDataScope: function() {
      if (this.form.roleId != undefined) {
        //this.form.deptIds = this.getDeptAllCheckedKeys();
        dataScope(this.form).then(response => {
          //this.msgSuccess("修改成功");
          this.$store.dispatch('snackbar/openSnackbar',{
            msg: '修改成功',
            color: 'success'
          })
          this.openDataScope = false;
          this.getList();
        });
      }
    },
    // 表格列点击删除按钮，切换确定删除按钮
    onClickDelete(item) {
      this.$set(item, 'showConfirmDelete', true);
      setTimeout(() => {
        this.$set(item, 'showConfirmDelete', false);
      }, 3500);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      // 关闭上一个消息弹窗
      this.$store.commit("snackbar/CLOSE_SNACKBAR");
      const roleIds = row.roleId || this.ids.map(item => item.roleId);
      await delRole(roleIds).then(res => {
        if (res) {
          // 使用全局消息提示
          this.$store.dispatch('snackbar/openSnackbar', {
            msg: '删除成功',
            color: 'success'
          })
          this.getList()
        }
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/role/export', {
        ...this.queryParams
      }, `role_${new Date().getTime()}.xlsx`)
    },
    // 创建时间 日期格式化
    formatDate (date) {
      if (!date) return null
      const [year, month, day] = date.split('-')
      return `${month}/${day}/${year}`
    },
    parseDate (date) {
      if (!date) return null
      const [month, day, year] = date.split('/')
      return `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`
    },
    openAllOnChange(val) {
      this.deptExpand = val
      this.$refs.deptTreeRef.updateAll();
    },
  }
};
</script>
